package com.bounds.dao.impl;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.bounds.entity.Pager;

public class BaseDaoImpl<T> extends JdbcDaoSupport {

	private Pager<T> page = new Pager<T>();

	protected String getExecuteSQL(String sql) {
		StringBuffer sqlbuf = new StringBuffer();
		//sqlbuf.append("select * from (select A$.*,rownum rn from(");
		sqlbuf.append(sql.replaceAll(";", ""));
		sqlbuf.append(" limit " +
				 ((page.getCurrentPageNo() - 1) * page.getPageSize()) 
				 +","+page.getPageSize());
		return sqlbuf.toString();
	}

	protected int getRowCount(String sql, Object[] params) {
		StringBuffer countSql = new StringBuffer("select count(*) count from ");
		countSql.append(
				sql.replaceAll(";", "").substring(
						sql.toLowerCase().indexOf("from") + 4)).toString();
		int allRows = 0;
		try {
			allRows = getJdbcTemplate()
					.queryForInt(countSql.toString(), params);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}catch(Exception e1){
			e1.printStackTrace();
		}
		page.setAllRows(allRows);
		return allRows;
	}
	
	protected int getRowCount1(String sql, Object[] params) {
		StringBuffer countSql = new StringBuffer("select count(*) count from ");
		countSql.append("("+sql+")");
		int allRows = 0;
		try {
			allRows = getJdbcTemplate()
					.queryForInt(countSql.toString(), params);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}catch(Exception e1){
			e1.printStackTrace();
		}
		page.setAllRows(allRows);
		return allRows;
	}

	protected void setPageNo(int pageNo) {
		page.setCurrentPageNo(pageNo);
	}

	protected void setPageSize(int pageSize) {
		page.setPageSize(pageSize);
	}

	protected void setAllPages(int allpages) {
		page.setAllPages(allpages);
	}

	protected void setData(List<T> data) {
		page.setData(data);
	}

	protected Pager<T> getPager() {
		return page;
	}

	protected void initPager() {
		page = new Pager<T>();
	}

	protected void initPager(int pageNo, int pageSize) {
		page = new Pager<T>(pageNo, pageSize);
	}


	public boolean hasTable(String tableName) {
		String sql = "SELECT COUNT(*) FROM user_tables t WHERE t.TABLE_NAME = ? ";
		try {
			return getJdbcTemplate().queryForInt(sql,
					new Object[] { tableName.toUpperCase() }) > 0;
		} catch (DataAccessException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return false;
	}
}